(function (window) {
    'use strict';

    /**
     * 用户信息对象
     * @type {{account: null, nickname: null, head: null}}
     */
    var user = {
        account: null,
        nickname: null,
        head: null

    };

    /**
     * @var DOM content 聊天消息承载
     * @var DOM msgText 文本消息输入
     * @var DOM sendText 文本消息发送
     * @var DOM msgImage 图片消息输入
     * @var DOM sendImage 图片消息发送
     * @var string key appkey
     * @var string roomId 聊天室编号
     * @var string name 用户名
     * @var string headUrl 头像地址
     */
    var content, msgText, submitText, msgImage, submitImage, key, roomId, pwd = '';

    /**
     * 消息刷新
     */
    var flash;


    /**
     * 模块启动函数,启动入口函数
     */
    function bootstrap() {
        if (typeof (IM) == 'undefined') {
            throw  new Error("connect IM server fail!");
        } else {
            console.log('connect to IM success!');
            var request = getRequest();
            console.log(request);
            key = request.key ? request.key : '1e6870eb-e813-4202-9d17-8740beebd04d';
            roomId = request.roomid ? request.roomid : '66605487';
            setUser(request);
            content = window.document.getElementById("im_content");
            msgText = window.document.getElementById("msg_text");
            submitText = window.document.getElementById("submit_text");
            msgImage = window.document.getElementById("msg_image");
            submitImage = window.document.getElementById("submit_image");

            if (bind()) {
                init();
            }

            delete IM.res.delRoom;
        }
        console.log("v server start");
    }

    /**
     * 初始化绑定DOM事件和开发接口
     */
    function bind() {
        var isAuto = true;

        //文本消息
        if (submitText && msgText) {
            submitText.onclick = function () {
                sendText(msgText.value);
            };
        } else {
            new V().sendText = sendText;
        }

        //图片消息
        if (submitImage && msgImage) {
            submitImage.onclick = function () {
                sendImage(msgImage.value);
            };
        } else {
            new V().sendImage = sendImage;
        }

        //聊天框
        if (content) {
            flash = flashMsg;
        } else {
            new V().flash = function (fuc) {
                if (typeof fuc == 'function') {
                    flash = fuc;
                } else {
                    throw new Error('fuc is function!');
                }
            };
            new V().init = init;
            isAuto = false;
        }

        return isAuto;
    }

    /**
     * 初始化IM服务
     */
    function init() {
        if (typeof flash != 'function') throw new Error('flash() is not initialized!');

        //绑定key
        IM.bind(key);

        // 连接到服务器,否则无法进行消息监听
        IM.onConnect(function () {
            console.log('Client has connected to the server!');
        });

        // 判断是否登录
        if (IM.isLogined()) {
            IM.login(user.account, pwd, function (data) {
                console.log('聊天室连接成功,状态:' + data);

                // 进入房间
                IM.enterRoom(roomId, function (data) {
                    console.log('进入房间成功:' + data);
                    getHistoryMegs();
                    on();
                }, function (data) {
                    throw new Error('聊天室进入失败,状态:' + data);
                });
            }, function (data) {
                throw new Error('账户登录失败,状态:' + data);
            });
        }
    }

    /**
     * 设置当前用户
     * @param request
     */
    function setUser(request) {
        if (!request.name && window.localStorage.getItem('user')) {
            user = JSON.parse(window.localStorage.getItem('user'));
            console.log(user);
        } else {
            var tag = Math.floor(Math.random() * 10000 + 1);
            user.account = request.name ? request.name : '游客' + tag;
            user.head = request.headurl ? request.headurl : '/image/default/avatar.png';
            window.localStorage.setItem('user', JSON.stringify(user));
        }
    }

    /**
     * 对外的接口
     * @constructor
     */
    function V() {
        if (!window.v) {
            window.v = {};
        }
        return window.v;
    }

    /**
     * 获取请求参数对象
     * @returns {*}
     */
    function getRequest() {
        var url = location.search;
        var theRequest = {};
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

    /**
     * 获取历史消息
     */
    function getHistoryMegs() {
        var getMsgData = {};
        getMsgData.receiverId = roomId;
        getMsgData.index = 1;
        getMsgData.count = 2;
        getMsgData.receiverType = IM_CONSTANT.CHAT_TYPE.ROOM;
        IM.res.getMsgs(getMsgData, function (data) {
            console.log('get history Msgs');
            data.forEach(function (item) {
                flash(item);
            });
        }, function (data) {
            console.log('get Msgss fail:' + data);
        });
    }


    /**
     * 默认刷新消息的方法
     * @param data
     */
    function flashMsg(data, isSend) {
        if (data.chatType == IM_CONSTANT.MSG_TYPE.IMG) {
            flashImage(data, isSend);
        } else {
            flashText(data, isSend);
        }

    }

    function flashText(data, isSend) {
        if (content) {
            var item = window.document.createElement('li');
            var div_text = window.document.createElement('div');
            var div_img = window.document.createElement('div');
            var img = window.document.createElement('img');
            var p_msg = window.document.createElement('p');
            var p_name = window.document.createElement('p');
            var time = window.document.createElement('p');
            var sendDate = new Date(data.sendTimeMs);

            time.innerHTML = sendDate.toLocaleTimeString();
            p_name.innerHTML = data.sendAccount;
            p_msg.innerHTML = data.content;

            var headUrl = data.extraData ? data.extraData : '/image/default/avatar.png';
            img.setAttribute("src", headUrl);

            div_text.appendChild(p_name);
            div_text.appendChild(p_msg);
            div_img.appendChild(img);
            item.appendChild(div_img);
            item.appendChild(time);
            item.appendChild(div_text);
            content.appendChild(item);
        }
    }

    function flashImage(data, isSend) {
        if (content) {
            var item = window.document.createElement('li');
            var div_text = window.document.createElement('div');
            var div_img = window.document.createElement('div');
            var img = window.document.createElement('img');
            var image = window.document.createElement('img');
            var p_name = window.document.createElement('p');
            var time = window.document.createElement('p');
            var sendDate = new Date(data.sendTimeMs);

            time.innerHTML = sendDate.toLocaleTimeString();
            p_name.innerHTML = data.sendAccount;
            image.setAttribute('src',data.content);

            var headUrl = data.extraData ? data.extraData : '/image/default/avatar.png';
            img.setAttribute("src", headUrl);

            div_text.appendChild(p_name);
            div_text.appendChild(p_msg);
            div_img.appendChild(img);
            item.appendChild(div_img);
            item.appendChild(time);
            item.appendChild(div_text);
            content.appendChild(item);
        }
    }

    /**
     * 启用监控事件
     */
    function on() {
        // 判断是否登录
        if (!IM.isLogined()) {
            // 开始监听消息
            console.log('stat watch msg');
            //IM_CONSTANT.CHAT_TYPE.ROOM, IM_CONSTANT.CHAT_TYPE.GROUP, IM_CONSTANT.CHAT_TYPE.USER
            IM.onMsg([IM_CONSTANT.CHAT_TYPE.ROOM], function (data) {
                console.log('on msg return:', data);

                console.log(data.sendTimeMs);

                // 添加消息时间
                if (data.sendTimeMs) {
                    data.sendTimeMs = (new Date()).valueOf();
                }

                flashMsg(data);
            });

            // 监听通知
            console.log('stat watch notifyss');
            IM.onNotify(IM_CONSTANT.NOTIFY.GROUP.DISMISS, function (data) {
                console.log('dismiss notify return:');
                console.log(data);
            });
            IM.onNotify(IM_CONSTANT.NOTIFY.GROUP.ENTER, function (data) {
                console.log('enter notify return:');
                console.log(data);
            });
            IM.onNotify(IM_CONSTANT.NOTIFY.GROUP.KICKOUT, function (data) {
                console.log('kickout notify return:');
                console.log(data);
            });
            IM.onNotify(IM_CONSTANT.NOTIFY.GROUP.LEAVE, function (data) {
                console.log('leave notify return:');
                console.log(data);
            });
        }
    }

    /**
     * 发送文本消息
     * @param msg_text
     */
    function sendText(msg_text) {
        var msg = {};
        msg.senderAccount = user.account;
        msg.chatType = IM_CONSTANT.CHAT_TYPE.ROOM;
        msg.content = msg_text.toString();
        msg.receiverId = roomId.toString();
        msg.extraData = user.head;
        msg.msgType = IM_CONSTANT.MSG_TYPE.TEXT;
        IM.sendText(msg, function (data) {
            var fmsg = {
                msgType: IM_CONSTANT.MSG_TYPE.TEXT,
                content: msg_text,
                sendAccount: user.account,
                extraData: user.head,
                sendTimeMs: (new Date()).valueOf()
            };

            console.log(msg, true);
            flash(fmsg);
            console.log('发送成功' + data);
        }, function (data) {
            console.log('发送失败' + data);
        });
    }

    /**
     * 发送图片消息
     */
    function sendImage() {
        var msg = {};
        msg.senderAccount = user.account;
        msg.chatType = IM_CONSTANT.CHAT_TYPE.ROOM;
        msg.receiverId = roomId.toString();
        msg.fileId = msgImage.getAttribute('id');
        msg.extraData = user.head;
        msg.msgType = IM_CONSTANT.MSG_TYPE.IMG;
        IM.sendImg(msg, function (data) {
            var imsg = {
                msgType: IM_CONSTANT.MSG_TYPE.IMG,
                sendAccount: user.account,
                content: data,
                extraData: user.head,
                sendTimeMs: (new Date()).valueOf()
            };
            flash(imsg, true);
            console.log('发送成功' + data);
        }, function (data) {
            console.log('发送失败' + data);
        });
    }

    /**
     * 加载完成后启动
     */
    window.onload = function () {
        bootstrap();
    };
})(window);